package com.ebs.md.fxmonitor.marketmonitor;

/**
 * Perforce Revision:
 *  $File: //depot/MarketData/fxmonitor/main/src/main/java/com/ebs/md/fxmonitor/marketmonitor/AbstractMonitorListenerAndForwarder.java $
 *  $Revision: #2 $  $Change: 114794 $  $DateTime: 2012/09/10 13:50:01 $  $Author: Arik.Sher $
 */

import java.io.Serializable;

import javax.jms.JMSException;

import org.springframework.util.Assert;

import com.ebs.commons.comp.IParsedPayload;
import com.ebs.commons.comp.IPubSubChannel;
import com.ebs.commons.logger.MessageText;

/**
 * Receiving ParsedPayload(by listening to Internal PubSub),
 * transforming it to F,
 * and forwarding in the InternalPubSub.
 * 
 * @param <F> type of object to forward
 */
public abstract class AbstractMonitorListenerAndForwarder<F extends Serializable>
extends AbstractMonitorListener
{
	
	protected boolean        toLogIgnored = false;
	protected IPubSubChannel pubChannel;
	protected String         publishToTopicName;

	public void setPublishToTopicName(String publishToTopicName) {
		this.publishToTopicName = publishToTopicName;
	}
	public void setPubChannel(IPubSubChannel pubChannel) {
		this.pubChannel = pubChannel;
	}
	public void setToLogIgnored(boolean toLogIgnored) {
		this.toLogIgnored = toLogIgnored;
	}

	public void init() {
//		super.init();
		Assert.notNull(pubChannel,         "'pubChannel' cannot be null");
		Assert.hasText(publishToTopicName, "'publishToTopicName' should contain text");
	}
	
	protected void handleParsedPayload(IParsedPayload payload) {
		F transformedObj = transform(payload);
		
		if ( transformedObj == null ) {
			if ( toLogIgnored && logger.isInfoEnabled() ) {
				logger.info(getClass().getSimpleName() + ": ignoring and not forwarding. source payload = " + payload);
			}
			return;
		}
		
		forward(transformedObj);
	}
	
	protected void forward(F obj) {
		try {
			pubChannel.submitMessage(publishToTopicName, obj);
		} catch (JMSException jmse) {
			logger.error(new MessageText("FXMON_0700003", shortClassName, "reasonable", jmse));
		} catch (Throwable t) {
			logger.error(new MessageText("FXMON_0700003", shortClassName, "unexpected", t));
		}
	}
	
	/**
	 * 
	 * @param payload
	 * @return the object to forward. might return null, than do not forward.
	 */
	abstract protected F transform(IParsedPayload payload)
	;
	
}
